package com.stella.ieproductivitybackend.service.impl;

import com.stella.ieproductivitybackend.entity.*;
import com.stella.ieproductivitybackend.mapper.BrandMapper;
import com.stella.ieproductivitybackend.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 品牌页服务层
 */
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;

    /**
     * 工厂列表
     */
    @Override
    public List<Factory> getFactoryList(String brand) {
        return brandMapper.getFactoryList(brand);
    }

    /**
     * 品牌列表
     */
    @Override
    public List<Brand> getBrandList() {
        return brandMapper.getBrandList();
    }

    /**
     * 品牌系列
     */
    @Override
    public List<Brand> getBrandSeries(String brand) {
        return brandMapper.getBrandSeries(brand);
    }

    /**
     * 型体数量
     */
    @Override
    public Integer getModelCount(String brand) {
        return brandMapper.getModelCount(brand);
    }

    /**
     * 型体列表
     */
    @Override
    public List<Model> getModelList(String brand) {
        return brandMapper.getModelList(brand);
    }

    /**
     * 搜索型体
     */
    @Override
    public List<Model> searchModel(String brand, String model) {
        return brandMapper.searchModel(brand, model);
    }

    /**
     * 纯粹达成率图表
     */
    @Override
    public Map<String, Object> getPureChart(String brand) {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<PureChart> pureChart = brandMapper.getPureChart(brand);
        List<Integer> thisPureChart = new ArrayList<>();
        List<Integer> lastPureChart = new ArrayList<>();

        PureChart pureChart1 = brandMapper.getTargetPureChart(brand);
        List<Integer> targetPureChart = new ArrayList<>();

        try {
            for (PureChart chart : pureChart) {
                for (Field field : chart.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Integer value = Integer.parseInt(field.get(chart).toString());
                    if (value != 0) {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisPureChart.add(value);
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastPureChart.add(value);
                        }
                    } else {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisPureChart.add(null);
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastPureChart.add(null);
                        }
                    }
                }
            }

            if (pureChart1 != null) {
                for (Field field : pureChart1.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(pureChart1);
                    if (value != null) {
                        String str = value.toString();
                        targetPureChart.add(Integer.valueOf(str));
                    } else {
                        targetPureChart.add(null);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        map.put("thisPureChart", thisPureChart);
        map.put("lastPureChart", lastPureChart);
        map.put("targetPureChart", targetPureChart);

        return map;
    }

    /**
     * 纯粹达成率详情
     */
    @Override
    public Map<String, Map<String, Map<String, Map<String, Integer>>>> getPureDetail(String brand) {
        Map<String, Map<String, Map<String, Map<String, Integer>>>> map = new LinkedHashMap<>();
        List<Pure> pureDetail = brandMapper.getPureDetail(brand);
        List<Pure> targetPureDetail = brandMapper.getTargetPureDetail(brand);

        int year = Calendar.getInstance().get(Calendar.YEAR);
        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "YY"};

        for (String m : month) {
            map.put(m, new LinkedHashMap<>());
        }

        for (Pure pure : pureDetail) {
            Map<String, Map<String, Map<String, Integer>>> factory = new LinkedHashMap<>();
            Map<String, Map<String, Integer>> type = new LinkedHashMap<>();
            Map<String, Integer> detail = new LinkedHashMap<>();

            detail.put("rate1", pure.getRate1());
            detail.put("rate2", pure.getRate2());
            detail.put("rate3", pure.getRate3());
            detail.put("rate4", pure.getRate4());
            detail.put("rate5", pure.getRate5());
            detail.put("rate6", pure.getRate6());

            if (Integer.parseInt(pure.getYear()) == year) {
                type.put("thisYear", detail);
            } else if (Integer.parseInt(pure.getYear()) == year - 1) {
                type.put("lastYear", detail);
            }

            factory.put(pure.getFactory(), type);

            if (map.get(pure.getMonth()) == null) {
                map.put(pure.getMonth(), factory);
            } else {
                if (map.get(pure.getMonth()).get(pure.getFactory()) == null) {
                    map.get(pure.getMonth()).put(pure.getFactory(), type);
                } else {
                    if (Integer.parseInt(pure.getYear()) == year) {
                        map.get(pure.getMonth()).get(pure.getFactory()).put("thisYear", detail);
                    } else if (Integer.parseInt(pure.getYear()) == year - 1) {
                        map.get(pure.getMonth()).get(pure.getFactory()).put("lastYear", detail);
                    }
                }
            }
        }

        for (Pure pure : targetPureDetail) {
            Map<String, Map<String, Map<String, Integer>>> factory = new LinkedHashMap<>();
            Map<String, Map<String, Integer>> type = new LinkedHashMap<>();
            Map<String, Integer> detail = new LinkedHashMap<>();

            detail.put("rate1", pure.getRate1());
            detail.put("rate2", pure.getRate2());
            detail.put("rate3", pure.getRate3());
            detail.put("rate4", pure.getRate4());
            detail.put("rate5", pure.getRate5());
            detail.put("rate6", pure.getRate6());

            type.put("thisTarget", detail);

            factory.put(pure.getFactory(), type);

            if (map.get(pure.getMonth()) == null) {
                map.put(pure.getMonth(), factory);
            } else {
                if (map.get(pure.getMonth()).get(pure.getFactory()) == null) {
                    map.get(pure.getMonth()).put(pure.getFactory(), type);
                } else {
                    map.get(pure.getMonth()).get(pure.getFactory()).put("thisTarget", detail);
                }
            }
        }

        return map;
    }

    /**
     * 入库标准秒值图表
     */
    @Override
    public Map<String, Object> getWarehousingChart(String brand) {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<WarehousingChart> warehousingChart = brandMapper.getWarehousingChart(brand);
        List<Integer> thisWarehousingChart = new ArrayList<>();
        List<Integer> lastWarehousingChart = new ArrayList<>();

        for (int i = 0; i < month.length; i++) {
            thisWarehousingChart.add(null);
            lastWarehousingChart.add(null);
        }

        for (WarehousingChart chart : warehousingChart) {
            if (Integer.parseInt(chart.getYear()) == year) {
                if ("年度".equals(chart.getMonth())) {
                    thisWarehousingChart.set(month.length - 1, chart.getTot_std_time2());
                } else {
                    thisWarehousingChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getTot_std_time2());
                }
            } else if (Integer.parseInt(chart.getYear()) == year - 1) {
                if ("年度".equals(chart.getMonth())) {
                    lastWarehousingChart.set(month.length - 1, chart.getTot_std_time2());
                } else {
                    lastWarehousingChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getTot_std_time2());
                }
            }
        }

        map.put("thisWarehousingChart", thisWarehousingChart);
        map.put("lastWarehousingChart", lastWarehousingChart);

        return map;
    }

    /**
     * 入库标准秒值图表详情
     */
    @Override
    public Map<String, List<Warehousing>> getWarehousingInfo(String brand) {
        Map<String, List<Warehousing>> map = new LinkedHashMap<>();
        List<Warehousing> warehousingInfo = brandMapper.getWarehousingInfo(brand);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};

        for (String m : month) {
            map.put(m, new ArrayList<>());
        }

        for (Warehousing warehousing : warehousingInfo) {
            if ("年度".equals(warehousing.getMonth())) {
                warehousing.setMonth("Total");
            }
            map.get(warehousing.getMonth()).add(warehousing);
        }

        return map;
    }

    /**
     * 入库标准秒值其他数据
     */
    @Override
    public Map<String, Object> getWarehousingOther(String brand) {
        Map<String, Object> map = new HashMap<>();

        List<String> factoryList = brandMapper.getWarehousingFactory(brand);
        List<String> yearList = brandMapper.getWarehousingYear(brand);
        List<String> monthList = brandMapper.getWarehousingMonth(brand);

        map.put("factoryList", factoryList);
        map.put("yearList", yearList);
        map.put("monthList", monthList);

        return map;
    }

    /**
     * 入库标准秒值详情
     */
    @Override
    public List<Warehousing> getWarehousingDetail(String brand, String factory, String year) {
        return brandMapper.getWarehousingDetail(brand, factory, year);
    }

    /**
     * 入库标准秒值对比
     */
    @Override
    public List<Warehousing> getWarehousingCompare(String brand, String factory1, String year1, String month1, String factory2, String year2, String month2) {
        return brandMapper.getWarehousingCompare(brand, factory1, year1, month1, factory2, year2, month2);
    }

    /**
     * 入库数量图表
     */
    @Override
    public Map<String, Object> getQuantityChart(String brand) {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<QuantityChart> quantityChart = brandMapper.getQuantityChart(brand);
        List<Integer> thisQuantityChart = new ArrayList<>();
        List<Integer> lastQuantityChart = new ArrayList<>();

        int thisTotal = 0;
        int lastTotal = 0;

        try {
            for (QuantityChart chart : quantityChart) {
                for (Field field : chart.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(chart);
                    if (value != null) {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisQuantityChart.add(Integer.parseInt(value.toString()));
                            thisTotal += Integer.parseInt(value.toString());
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastQuantityChart.add(Integer.parseInt(value.toString()));
                            lastTotal += Integer.parseInt(value.toString());
                        }
                    } else {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisQuantityChart.add(null);
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastQuantityChart.add(null);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        thisQuantityChart.add(thisTotal);
        lastQuantityChart.add(lastTotal);

        map.put("thisQuantityChart", thisQuantityChart);
        map.put("lastQuantityChart", lastQuantityChart);

        return map;
    }

    /**
     * 入库数量详情
     */
    @Override
    public Map<String, List<Quantity>> getQuantityDetail(String brand) {
        Map<String, List<Quantity>> map = new LinkedHashMap<>();
        List<Quantity> quantityDetail = brandMapper.getQuantityDetail(brand);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};

        for (String m : month) {
            map.put(m, new ArrayList<Quantity>());
        }

        for (Quantity quantity : quantityDetail) {
            map.get(quantity.getMonth()).add(quantity);
        }

        return map;
    }

    /**
     * 直工 PPH 选项
     */
    @Override
    public Map<String, Object> getDirectOption(String brand) {
        Map<String, Object> map = new HashMap<>();

        List<String> factoryList = brandMapper.getDirectFactory(brand);
        List<String> yearList = brandMapper.getDirectYear(brand);
        List<String> monthList = brandMapper.getDirectMonth(brand);
        List<String> modelList = brandMapper.getDirectModel(brand);
        List<String> operationList = brandMapper.getDirectOperation(brand);

        map.put("factoryList", factoryList);
        map.put("yearList", yearList);
        map.put("monthList", monthList);
        map.put("modelList", modelList);
        map.put("operationList", operationList);

        return map;
    }

    /**
     * 直工 PPH 详情
     */
    @Override
    public List<DirectPPH> getDirectPPH(String brand, String factory, String year, String month, String model, String operation) {
        return brandMapper.getDirectPPH(brand, factory, year, month, model, operation);
    }
}